package text
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.text.Font;

	public class SnapsFontLoader extends EventDispatcher
	{
		
		public static const FONT_LOADED:String = "fontLoaded";
		private var _loadedFont:Class;
		private var _fontid:String;
		private var _fontname:String;
		
		
		public function get fontname():String{	return _fontname;	}
		
		public function get fontid():String{	return _fontid;	}
		
		public function get loadedFont():Class{	return _loadedFont	}
		
		public function SnapsFontLoader()
		{
		}
		
		public function load($id:*, $name:String = ""):void
		{
			loadNormal($id, $name);
			if($id is String)
			{
				if($id == "snaps_BomnalM")
					loadBold($id, $name);
			}
			else
			{
				if($id.@id == "snaps_BomnalM")
					loadBold($id, $name);
			}
		}
		
		public function loadNormal($id:*, $name:String = ""):void
		{
			var loader:Loader = new Loader;
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, normalFontLoaded);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, fontError);
			if($id is String)
			{
				_fontid = $id;
				_fontname = $name;
			}
			else
			{
				_fontid = $id.@id;
				_fontname = $id.@name;
				
			}
			
			loader.load(new URLRequest("assets/fonts/"+_fontid+".swf"));
			
		}
		
		public function loadBold($id:*, $name:String = ""):void
		{
			var loader:Loader = new Loader;
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, boldFontLoaded);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, fontError);
			if($id is String)
			{
				_fontid = $id;
				_fontname = $name;
			}
			else
			{
				_fontid = $id.@id;
				_fontname = $id.@name;
				
			}
			
			loader.load(new URLRequest("assets/fonts/"+_fontid+"_Bold.swf"));
			
		}
		
		private function boldFontLoaded(e:Event):void
		{
			
		}
		
		private function normalFontLoaded(e:Event):void
		{
			//e.target.removeEventListener(Event.COMPLETE, fontLoaded);
			
			var url:String = e.target.url;
			var fontClassName:String;
			var pattern:RegExp = /\\/g;
			url = url.replace(pattern, "/");
			url = url.substr(url.lastIndexOf("/")+1);
			fontClassName = url.substr(0, url.lastIndexOf(".swf"));
			
			//_loadedFont = e.target.applicationDomain.getDefinition(fontClassName) as Class;
			
			dispatchEvent(new Event(FONT_LOADED));
			
			//Font.registerFont(_loadedFont);
			
			//viewFontList();
		}
		
		private function fontError(e:IOErrorEvent):void
		{
			trace(e.text);
		}
		
		private function viewFontList():void
		{
			var arr:Array = Font.enumerateFonts();
			for each(var obj:Font in arr)
			{
				trace(obj.fontName);
			}
		}
	}
}